#include <stdio.h>
#include <istream>
#include <cassert>
#include "components/count_letters_in_file.h"
using std::string;
using std::vector;

//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

//		count_letters_in_file_c

//			count number of specified letters occurring in a file

//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
/*bool count_letters_in_file_c(	const std::string&		file_name,
							const std::string&		search_letters,
							t_progress_indicator	seq_progress,
							std::vector<unsigned>&	results)
{
	// make sure some letters
	assert(search_letters.length());
	
	vector<unsigned>(search_letters.length()).swap(results);
	if (!results.size())
		return true;

	char buf [65536];
	
	FILE* letter_file = fopen (file_name.c_str(), "rS");
	if (!letter_file)
		return false;
    size_t read_cnt;
	{
		while ((read_cnt = fread(buf, 1,  sizeof(buf), letter_file)) != 0)
		{
			for (unsigned i = 0; i < search_letters.length(); ++i)
			{
				unsigned letter_cnt = 0;
				char test_char = search_letters[i];
				char* offset = buf;
				char* end = buf + read_cnt;
				while( offset < end)
				{
					if (!(offset = (char*)(memchr(offset, test_char, end - offset))))
						break;
					++offset;
					++letter_cnt;
				}
				results[i] += letter_cnt;
			}
			seq_progress++;
		}
	}
	fclose(letter_file);
	return true;
}
*/
//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

//		count_letters_in_file

//			count number of specified letters occurring in a file

//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
std::vector<unsigned> count_letters_in_file(	std::istream&			letter_file,
											const std::string&			search_letters,
											const t_progress_indicator&	seq_progress)
{
	t_progress_indicator dots(seq_progress);
	// make sure some letters
	assert(search_letters.length());
	if (!search_letters.length())
		return std::vector<unsigned> ();
	
	std::vector<unsigned> results(search_letters.length());


	char buf [65536];

	size_t read_cnt;
	{
		letter_file.read(buf, sizeof(buf));
		while ((read_cnt = letter_file.gcount()) != 0)
		{
			for (unsigned i = 0; i < search_letters.length(); ++i)
			{
				unsigned letter_cnt = 0;
				char test_char = search_letters[i];
				char* offset = buf;
				char* end = buf + read_cnt;
				while( offset < end)
				{
					if (!(offset = (char*)(memchr(offset, test_char, end - offset))))
						break;
					++offset;
					++letter_cnt;
				}
				results[i] += letter_cnt;
			}
			dots++;
			letter_file.read(buf, sizeof(buf));
		}
	}
	return results;
}

